import router from '../router'
import store from '../store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({ showSpinner: false })// NProgress Configuration

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    /* has token 如果已经登录跳转至首页防止重复登录 */
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      store.dispatch('SetNavTitle', to.meta.title)
      next()
    }
  } else {
    /* has no token */
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login' })
    }
    NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
